/**
 * 用户相关服务
 */
const https = require('../utils/request.js');
const api = require('../config/api.js');


/**
 * Promise封装wx.checkSession
 */
function checkSession() {
	return new Promise(function (resolve, reject) {
		wx.checkSession({
			success: function () {
				resolve(true);
			},
			fail: function () {
				reject(false);
			}
		})
	});
}

/**
 * Promise封装wx.login
 */
function login() {
	return new Promise(function (resolve, reject) {
		wx.login({
			success: function (res) {
				console.log('获取code', res)
				if (res.code) {
					resolve(res);
				} else {
					reject(res);
				}
			},
			fail: function (err) {
				reject(err);
			}
		});
	});
}

/**
 * 调用微信登录
 */
function loginByWeixin() {
	return new Promise(function (resolve, reject) {
		return login().then((res) => {
			//登录远程服务器
			https.request(api.AuthLogin, {
				code: res.code
			}, 'POST').then(res => {
				console.log('登录成功', res)
				if (res.error_code == 0) {
					// 储存用户唯一标识
					// wx.setStorageSync('token', res.data.token);
					wx.setStorageSync('openid', res.data.openid);
					resolve(res);
				} else {
					reject(res);
				}
			}).catch((err) => {
				console.log('登录失败', err)
				reject(err);
			});
		}).catch((err) => {
			console.log('获取code失败', err)
			reject(err);
		})
	});
}

/**
 * 判断用户是否登录
 */
function checkLogin() {
	return new Promise(function (resolve, reject) {
		//todo: token逻辑暂时没有，用appid代替
		// if (wx.getStorageSync('userInfo') && wx.getStorageSync('token')) {
		if (wx.getStorageSync('userInfo') && wx.getStorageSync('openid')) {
			console.log('1存在缓存的用户信息')
			checkSession().then(() => {
				resolve(true);
			}).catch(() => {
				reject(false);
			});
		} else {
			console.log('2不存在缓存的用户信息')
			reject(false);
		}
	});
}

/**
 * 判断用户是否注册
 */
function checkRegister() {
	return new Promise(function (resolve, reject) {
		wx.showLoading()
		loginByWeixin().then(res => {
			wx.hideLoading()
			//存储用户信息
			if (res.data.message) {
				// 未注册,跳转注册
				wx.navigateTo({
					url: "/pages/my/register/register"
				});
			} else {
				let {
					id,
					name,
					avatar,
					iphone,
					code
				} = res.data;
				let params = {
					id,
					name,
					iphone,
					code,
					avatar
				};
				console.log('保存用户信息', params);
				wx.setStorageSync('userInfo', params);
				resolve(true);
			}
		}).catch(e => {
			console.log('登录', e)
			wx.hideLoading()
			wx.showToast({
				icon: 'none',
				title: '登录异常，请稍后再试'
			})
			reject(false);
		})

	})
}



module.exports = {
	checkLogin,
	checkRegister
};